package com.szxy.service.impl;

import com.szxy.mapper.OrderTblMapper;
import com.szxy.pojo.OrderTbl;
import com.szxy.service.OrderService;
import com.szxy.service.feign.AccountServiceFeign;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: zwz
 * @Date:2020/7/15 21:28
 * @Description:com.szxy.service.impl
 * @Version:1.0
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderTblMapper orderTblMapper;
//    @Autowired
//    private AccountSereviceApi accountSereviceApi;
    @Autowired
    private AccountServiceFeign accountServiceFeign;

    /**
     * 记录日志
     */
    private static final Logger logger =
            LoggerFactory.getLogger(OrderServiceImpl.class);

    @Transactional
    @Override
    public void addOrder(String userId, String productId, int count) {
        logger.info("开始下单 用户：{}，商品：{}，商品数量： {}",userId, productId, count);
        // 1. 扣除用户账号金额
        Integer money = cal(productId, count);
        //ResponseEntity<Void> responseEntity = this.accountSereviceApi.deBit(userId, money);
        ResponseEntity<Void> responseEntity = this.accountServiceFeign.deBin(userId, money);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException("远程调用 Storage 服务失败 ...");
        }
        //2. 下订单
        OrderTbl order = new OrderTbl();
        order.setCount(count);
        order.setMoney(money);
        order.setUserId(userId);
        this.orderTblMapper.insert(order);
        logger.info("下单处理完成，用户： {}, 扣除账户金额为：{}", userId, money);
        String xid = RootContext.getXID();
        System.out.println("全局事务 xid = " + xid);
    }

    /**
     * 计算商品金额
     * @param productId
     * @param count
     * @return
     */
    private Integer cal(String productId, int count) {
        // 这里没有商品表，采用 money 替代查询商品金额
        int money = 0;
        if("HUAWEI_001".equals(productId)) {
            money = 2000;
        }else if("XIAOMI_002".equals(productId)) {
            money = 1000;
        }else {
            money = 9999;
        }
        return money * count;
    }
}
